<?php
namespace app\api\service;

use app\common\model\Order;
use app\common\model\User;
use app\common\model\Bank;
use app\common\model\Detailed;
use app\common\model\UserAmount;
use app\common\model\Withdrawal;
use app\Response;

class UserAmountService
{

    /*** 我的钱包
     */
    public static function mineWalletService($user_id){
        $userInfo = User::userInfo(["uid"=>$user_id]);
        if(!in_array($userInfo['type'],[22,23,24])){
            return Response::wrapError(0,"账户非用户!");
        }
        if($userInfo['enable'] == 0){
            return Response::wrapError(-200,"此账户已被禁用,如有疑问请联系平台客服!");
        }

        $userAmount = UserAmount::userAmountInfo(['uid'=>$user_id]);
        $info = [];
        if($userAmount['arrears'] > 0){
            $info['arrears'] = $userAmount['arrears'];
        }else{
            $info['balance'] = $userAmount['balance'];
            $info['withdrawal'] = Withdrawal::withdrawalBalanceCount([['uid','=',$user_id],['type','=',1],['state','in','0,1']]);
        }

        if(empty($User['pay_password'])){//未设置支付密码
            $info['password_state'] = 0;
        }else{//已设置支付密码
            $info['password_state'] = 1;
        }

        $bank = Bank::bankList(['uid'=>$user_id,'enable'=>1],1,10);
        if(empty($bank)){
            $info['bank'] = [];
        }else{
            $info['bank'] = [];
            foreach($bank as $item){
                $b = [];
                $b['id'] = $item['id'];
                $b['type'] = $item['type'];
                $b['bank_name'] = $item['bank_name'];
                $b['bank_card'] = self::bankCardEdit($item['bank_type'],$item['bank_card']);
                $b['account_holder'] = self::alipayUsername($item['account_holder']);
                $info['bank'][] = $b;
            }
        }

        return Response::wrapData($info);
    }

    /*** 下级用户-下单列表
     * @param $user_id  int 用户ID
     * @param $page int 页码
     * @param $num int 个数
     * @param $type int 状态 1未分成 2已分成 3全部
     * @return json
    */
    public static function nextUserOrderListService($user_id,$page,$num,$type){
        $userInfo = User::userInfo(["uid"=>$user_id]);
        if($userInfo['type'] != 22){
            return Response::wrapError(0,"账户非团长!");
        }
        if($userInfo['enable'] == 0){
            return Response::wrapError(-200,"此账户已被禁用,如有疑问请联系平台客服!");
        }
        $where[] = ["o.sup_uid","=",$user_id];
        $where[] = ["o.enable","=",1];
        $where[] = ["o.state","<>",0];
        if($type == 1){
            $where[] = ["o.com_state","=",1];
        }elseif($type == 2){
            $where[] = ["o.com_state","=",2];
        }
        $data = [];
        $order = Order::nextUserOrderList($where,$page,$num);
        if(!empty($order)){
            $order = $order->toArray();
            foreach($order as $k => $v){
                $order[$k]["addtime"] = !empty($v["addtime"])?date("Y-m-d H:i:s",$v["addtime"]):"";
            }
            $sum_where[] = ["sup_uid","=",$user_id];
            $sum_where[] = ["enable","=",1];
            $sum_where[] = ["state","<>",0];
            if($type == 1){
                $sum_where[] = ["com_state","=",1];
            }elseif($type == 2){
                $sum_where[] = ["com_state","=",2];
            }
            $count = Order::nextUserOrderListCount($where);
            $data["list"] = $order;
            $sum = Order::orderSum($sum_where,"commission_info->sup_commission_price");
            $data["sum"] = number_format($sum,2);
        }else{
            $data["sum"] = 0;
            $data["list"] = array();
            $count = 0;
        }
        return Response::wrapData($data,$count);
    }

    /*** 赏金记录
     * @param $user_id int
     * @param $data int
     * @return json
     */
    public static function userDetailedService($user_id,$data){
        $userInfo = User::userInfo(["uid"=>$user_id]);
        if(!in_array($userInfo['type'],[22,23,24])){
            return Response::wrapError(0,"账户非用户!");
        }
        if($userInfo['enable'] == 0){
            return Response::wrapError(-200,"此账户已被禁用,如有疑问请联系平台客服!");
        }
        $info = [];
        if($data['type'] == 1){ //余额明细 含提现冻结
            $where = [];
            $where[] = ['uid','=',$user_id];
            $where[] = ['amount_money','>',0];
            $where[] = ['type','in',"withdrawal_freeze,withdrawal_fee,withdrawal_success,withdrawal_unfreeze"];
            $detailed = Detailed::detailedList($where,$data['page'],$data['num']);
            foreach ($detailed as $item){
                $i = [];
                if(strpos($item['remarks'],'提现冻结') !== false){ //如果是提现冻结   替换成提现中
                    $i['remarks'] = str_replace('提现冻结','提现中',$item['remarks']);
                }else{
                    $i['remarks'] = $item['remarks'];
                }
                $i['state'] = $item['state'];
                $i['amount_money'] = $item['amount_money'];
                $i['balance'] = $item['balance'];
                $i['addtime'] = date('Y-m-d H:i',$item['addtime']);
                if(in_array($item['type'],['withdrawal_freeze','withdrawal_success','withdrawal_unfreeze'])){ //如果是提现
                    $withdrawal = Withdrawal::withdrawalView(['id'=>$item['to_id']]);
                    $i['fee'] = $withdrawal['fee'];
                    $i['no_order'] = $withdrawal['no_order'];
                }
                $info[] = $i;
            }
            $count = Detailed::detailedCount($where);
        }elseif($data["type"] == 0){
            $where = [];
            $where[] = ['d.uid','=',$user_id];
            $where[] = ['d.amount_money','>',0];
            $where[] = ['d.type','in',"after_sales_admin"];
            $detailed = Detailed::afterDetailedList($where,$data['page'],$data['num']);
            foreach ($detailed as $item){
                $i = [];
                $i['state'] = $item['state'];
                $i['amount_money'] = $item['amount_money'];
                $i['balance'] = $item['balance'];
                $i['addtime'] = date('Y-m-d H:i',$item['addtime']);
                $i['fee'] = $item['fee'];
                $i['no_order'] = $item['o_pro_num'];
                $i['remarks'] = $item['remarks'];
                $info[] = $i;
            }
            $count = Detailed::afterDetailedListCount($where);
        }
        return Response::wrapData($info,$count);
    }





    /*** 修改支付密码
     * @param $user_id int
     * @param $data array
     * @return json
     */
    public static function editPayPassWordService($user_id,$data){
        $User = User::userInfo(["uid"=>$user_id]);
        if(empty($User)){
            return Response::wrapError('非法请求',-200);
        }
        if(!in_array($User['type'],[22,23,24])){
            return Response::wrapError(0,"账户非用户!");
        }
        if($User['enable'] == 0){
            return Response::wrapError(-200,"此账户已被禁用,如有疑问请联系平台客服!");
        }

        $res =  \app\common\model\User::forgetPayPassword($User,$data['payPassword']);
        if($res){
            return Response::wrapData();
        }else{
            return Response::wrapError(0,"密码修改失败,请稍后重试");
        }
    }


    /*** 绑定银行卡
     * @param $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function bankAddService($user_id,$data){
        if($data['bankType'] == 1){
            if(empty($data['bankName'])){
                return Response::wrapError("银行名称必须选择");
            }
            if(empty($data['province'])){
                return Response::wrapError("省必须选择");
            }
            if(empty($data['city'])){
                return Response::wrapError("市必须选择");
            }
            if(empty($data['openBank'])){
                return Response::wrapError("开户行必须输入");
            }
        }
        $User = User::userInfo(["uid"=>$user_id]);
        if(empty($User)){
            return Response::wrapError('非法请求',-200);
        }
        if(!in_array($User['type'],[22,23,24])){
            return Response::wrapError('账户非买家用户',-200);
        }
        if($User['enable'] == 0){
            return Response::wrapError('此账户已被禁用,如有疑问请联系客服人员',-200);
        }
        $userBank = Bank::bankInfo(['uid'=>$user_id,'type'=>$data['bankType'],'enable'=>1]);

        if($userBank){
            return Response::wrapError('您已绑定了此类型,无需再绑定，如需修改请联系客服');
        }
        if($data['bankType'] == 1){ //绑定银行卡
            $bank = [
                'uid' => $user_id,
                'type' => $data['bankType'],
                'bank_name' => $data['bankName'],
                'bank_card' => $data['bankCard'],
                'province' => $data['province'],
                'city' => $data['city'],
                'open_bank' => $data['openBank'],
                'account_holder' => $data['accountHolder'],
                'addtime' => time(),
            ];
        }else{ //绑定支付宝
            $bank = [
                'uid' => $user_id,
                'type' => $data['bankType'],
                'bank_name' => 'alipay',
                'bank_card' => $data['bankCard'],
                'account_holder' => $data['accountHolder'],
                'addtime' => time(),
            ];
        }
        Bank::bankAdd($bank);
        return Response::wrapData();
    }


    /**** 解绑银行卡 或 支付宝
     * @param $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function bankDelService($user_id,$data){
        $User = User::userInfo(["uid"=>$user_id]);
        if(empty($User)){
            return Response::wrapError('非法请求',-200);
        }
       if(!in_array($User['type'],[22,23,24])){
            return Response::wrapError('账户非买家用户',-200);
        }
        if($User['enable'] == 0){
            return Response::wrapError('此账户已被禁用,如有疑问请联系客服人员',-200);
        }

        $userBank = Bank::bankInfo(['id'=>$data['bankId'],'enable'=>1]);
        if(empty($userBank)){
            return Response::wrapError('已解绑此卡片');
        }else{
            if($userBank['uid'] != $user_id){
                return Response::wrapError('非法请求');
            }
        }
        Bank::BankEdit(['id'=>$data['bankId']],['enable'=>0,'relievetime'=>time()]);
        return Response::wrapData();
    }


    /*** 银行卡截取后四位  支付宝手机号码隐藏中间四位   邮箱隐藏中间部分
     * @param $bankType
     * @param $bankCord
     * @return false|string|string[]
     */
    public static function bankCardEdit($bankType,$bankCord){
        if($bankType == 1){
            return substr($bankCord,-4);
        }else{
            return  self::alipayName($bankCord);
        }
    }

    //支付宝账号  根据手机号码或者邮箱 隐藏中间字段
    private static function alipayName($alipayName){
        if(strpos($alipayName,'@') !== false){ //为邮箱
            return substr($alipayName,0,3) .'****'. strstr($alipayName, '@');
        }else{ //为手机号码
            return substr_replace($alipayName,'****',3,4);
        }
    }

    //截取真实姓名
    private static function alipayUsername($alipayUsername){
        return mb_strcut($alipayUsername, 0, 3, 'utf-8') . '**';
    }

}